/**
 * Created by tanbingqin on 2020/1/16.
 */
import {messages} from "share/common";
import React from 'react';
import {connect} from "react-redux";
import { message, Modal, Button } from 'antd';
import approveService from 'containers/approve/approve.service';
import Comment from 'components/template/comment';
import FileUpload from 'components/file-upload';
import IeFileUpload from 'components/template/ie-file-upload/ie-file-upload';
import errorMessage from 'share/errorMessage';

class ApproveMention extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      showMention: false, //是否展示控件，重新render控件使用
      comment: null,
      attachments: []
    }
  }

  componentWillReceiveProps(nextProps) {
    const { mentionVisible } = this.props;
    if (!mentionVisible && nextProps.mentionVisible) {
      this.setState({showMention: true});
    }
    if (mentionVisible && !nextProps.mentionVisible) {
      this.setState({comment: null, showMention: false});
    }
  }

  //isSuccess 是否是成功的返回
  closeMentionModal = (isSuccess) => {
    const { onClose } = this.props;
    if (onClose) {
      onClose(isSuccess);
    }
  };

  handleMention = () => {
    const { entities } = this.props;
    const { comment, attachments } = this.state;

    if (!comment || !comment.text) {
      message.error(messages('common-1.key229')/*请输入评论*/);
      return;
    }
    //算长度的时候把换行过滤掉，与控件内部长度计算逻辑一致
    let strText = comment.text.replace(/^\n/g, '').replace(/\n$/g, '');
    if (strText.length > 500) {
      message.error(messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/);
      return;
    }
    let params = {
      entityOID: entities.entityOID,
      entityType: entities.entityType,
      operationDetail: comment.text,
      historyDiscussDetail: comment.html,
      attachmentOIDs: [],
      discussUsers: []
    };
    attachments.forEach(img => {
      params.attachmentOIDs.push(img.attachmentOID);
    });
    comment.list && comment.list.forEach(user => {
      params.discussUsers.push({
        userOID: user.userOID,
        fullName: user.userName
      });
    });
    this.setState({loading: true});
    approveService.postMention(params).then(res => {
      this.setState({
        loading: false,
        attachments: []
      });
      message.success(messages('common.operate.success')/*操作成功*/);
      this.closeMentionModal(true);
    }).catch(err => {
      errorMessage(err.response);
      this.setState({loading: false});
    });
  };

  handleChange = (value, key) => {
    this.setState({[key]: value});
  };

  render() {
    const { mentionVisible, customFormPropertyMap } = this.props;
    const { loading, showMention, attachments } = this.state;
    let signCompanyOIDs = (customFormPropertyMap && customFormPropertyMap['approval_add_sign_scope']) ? JSON.parse(customFormPropertyMap['approval_add_sign_scope']).companyOIDs : [];
    return (
      <div>
        <Modal
          width={700}
          className=""
          title={messages('common-1.key197')/*评论*/}
          visible={mentionVisible}
          onCancel={() => this.closeMentionModal(false)}
          maskClosable={false}
          destroyOnClose={true}
          footer={[
            <Button key="back" onClick={() => this.closeMentionModal(false)}>{messages('common.cancel')/*取消*/}</Button>,
            <Button key="submit" type="primary" loading={loading} onClick={() => this.handleMention()}>{messages('common.ok')/*确定*/}</Button>
          ]}
        >
          {showMention && (
            <div>
              <Comment onChange={value => this.handleChange(value, 'comment')} companyOIDs={signCompanyOIDs} />
              {!window.ISIE9 && (
                <div style={{marginTop: 20}}>
                  <FileUpload
                    attachmentType="INVOICE_IMAGES"
                    defaultFileList={attachments}
                    onChange={value => this.handleChange(value, 'attachments')}
                    maxNum={3}
                    showMaxNum
                    fileSize={10}
                    showFileName
                    isShowExtraPrompt
                  />
                </div>
              )}
              {window.ISIE9 && (
                <div style={{marginTop: 20}}>
                  <IeFileUpload
                    attachmentType="INVOICE_IMAGES"
                    defaultFileList={attachments}
                    onChange={value => this.handleChange(value, 'attachments')}
                    maxNum={3}
                    showMaxNum
                    fileSize={10}
                  />
                </div>
              )}
            </div>
          )}
        </Modal>
      </div>
    )
  }

}

ApproveMention.propTypes = {
  mentionVisible: React.PropTypes.bool,
  onClose: React.PropTypes.func,
  entities: React.PropTypes.object,//评论所需字段
  customFormPropertyMap: React.PropTypes.object
};

ApproveMention.defaultProps = {
  mentionVisible: false,
  onClose: () => {},
  entities: {},
  customFormPropertyMap: {}
};

function mapStateToProps(state) {
  return {}
}

export default connect(mapStateToProps)(ApproveMention);

